import { useRequest } from 'alova/client'
import {
  Card,
  Typography,
  Skeleton,
  Descriptions,
  Divider,
  Button,
  Image,
} from 'antd'
import { useNavigate, useParams } from 'react-router-dom'
import { formatDate, isVideo, isImage } from '../uitls/common'
import { useState, useEffect } from 'react'

const MaintainDetail: React.FC = () => {
  const { id } = useParams()
  const navigate = useNavigate()
  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewUrl, setPreviewUrl] = useState('')

  const {
    data,
    loading,
    send: fetchDetail,
  } = useRequest(
    () => {
      return Apis.mt.Detail({
        pathParams: {
          maintainBatch: id ?? '',
        },
      })
    },
    {
      immediate: false,
    }
  )

  useEffect(() => {
    if (id) {
      fetchDetail()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 处理预览图片或视频
  const handlePreview = (url: string) => {
    setPreviewUrl(url)
    setPreviewVisible(true)
  }

  // 渲染附件列表
  const renderFileList = () => {
    if (!data?.file || data.file.length === 0) {
      return <div>暂无附件</div>
    }

    return (
      <div className="flex flex-wrap gap-4">
        {data.file.map((file, index) => {
          if (file.url) {
            if (isImage(file.url)) {
              return (
                <div key={index} className="w-24 h-24 relative">
                  <Image
                    src={file.url}
                    alt={file.mediaName || `附件${index + 1}`}
                    className="w-full h-full object-cover cursor-pointer"
                    onClick={() => handlePreview(file.url!)}
                    preview={false}
                  />
                  <div className="text-center text-xs mt-1 truncate">
                    {file.mediaName || `附件${index + 1}`}
                  </div>
                </div>
              )
            } else if (isVideo(file.url)) {
              return (
                <div key={index} className="w-24 h-24 relative">
                  <div
                    className="w-full h-full bg-gray-200 flex items-center justify-center cursor-pointer"
                    onClick={() => handlePreview(file.url!)}
                  >
                    <span>视频</span>
                  </div>
                  <div className="text-center text-xs mt-1 truncate">
                    {file.mediaName || `视频${index + 1}`}
                  </div>
                </div>
              )
            } else {
              return (
                <div key={index} className="w-24 h-24 relative">
                  <div className="w-full h-full bg-gray-100 flex items-center justify-center">
                    <a
                      href={file.url}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      下载文件
                    </a>
                  </div>
                  <div className="text-center text-xs mt-1 truncate">
                    {file.mediaName || `文件${index + 1}`}
                  </div>
                </div>
              )
            }
          }
          return null
        })}
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col px-12 py-4">
      <Card className="mb-4">
        <div className="flex justify-between">
          <span className="space-holder"></span>
          <Typography.Title level={4}>维保详情</Typography.Title>
          <Button type="primary" onClick={() => navigate(-1)}>
            返回
          </Button>
        </div>
        {loading ? (
          <Skeleton className="w-full" active paragraph={{ rows: 10 }} />
        ) : (
          <div>
            <Descriptions bordered>
              <Descriptions.Item label="维保记录ID" span={3}>
                {data?.id}
              </Descriptions.Item>
              <Descriptions.Item label="维保批次号" span={3}>
                {data?.maintainBatch}
              </Descriptions.Item>
              <Descriptions.Item label="维保时间" span={3}>
                {data?.time ? formatDate(data.time) : ''}
              </Descriptions.Item>
            </Descriptions>

            <Divider />

            <Typography.Title level={5}>用户信息</Typography.Title>
            <Descriptions bordered>
              <Descriptions.Item label="户号" span={1}>
                {data?.houseCode}
              </Descriptions.Item>
              <Descriptions.Item label="户主名称" span={2}>
                {data?.name}
              </Descriptions.Item>
              <Descriptions.Item label="联系电话" span={1}>
                {data?.contactMobile}
              </Descriptions.Item>
              <Descriptions.Item label="合同号" span={2}>
                {data?.contractCode}
              </Descriptions.Item>
              <Descriptions.Item label="小区名称(地址)" span={3}>
                {data?.address}
              </Descriptions.Item>
            </Descriptions>

            <Divider />

            <Typography.Title level={5}>维保信息</Typography.Title>
            <Descriptions bordered>
              <Descriptions.Item label="维保过程" span={3}>
                {data?.maintenanceContent || '暂无记录'}
              </Descriptions.Item>
              <Descriptions.Item label="维保结果" span={3}>
                {data?.maintenanceResult || '暂无记录'}
              </Descriptions.Item>
            </Descriptions>

            <Divider />

            <Typography.Title level={5}>附件资料</Typography.Title>
            {renderFileList()}
          </div>
        )}
      </Card>

      {/* 图片/视频预览 */}
      {previewVisible && isImage(previewUrl) && (
        <Image
          style={{ display: 'none' }}
          src={previewUrl}
          preview={{
            visible: previewVisible,
            onVisibleChange: (visible) => setPreviewVisible(visible),
          }}
        />
      )}

      {/* 视频预览弹窗 - 这里可以根据需要实现视频预览 */}
      {previewVisible && isVideo(previewUrl) && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            zIndex: 1000,
          }}
          onClick={() => setPreviewVisible(false)}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            style={{ width: '80%', maxWidth: '800px' }}
          >
            <video
              src={previewUrl}
              controls
              style={{ width: '100%', maxHeight: '80vh' }}
              autoPlay
            />
          </div>
        </div>
      )}
    </div>
  )
}

export default MaintainDetail
